//
//  DismissKeyboardOnTap.swift
//  xz-app
//
//  Created by chen on 2025/5/6.
//
import SwiftUI

struct DismissKeyboardOnTap: ViewModifier {
    func body(content: Content) -> some View {
        content
            .onAppear {
                DispatchQueue.main.async {
                    guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                          let window = windowScene.windows.first else { return }
                    
                    let tapGesture = UITapGestureRecognizer(
                        target: window,
                        action: #selector(UIView.endEditing)
                    )
                    tapGesture.requiresExclusiveTouchType = false
                    tapGesture.cancelsTouchesInView = false
                    tapGesture.delegate = SimpleTapGestureDelegate.shared
                    window.addGestureRecognizer(tapGesture)
                }
            }
    }
}

// 添加一个手势代理类来处理手势冲突
class SimpleTapGestureDelegate: NSObject, UIGestureRecognizerDelegate {
    static let shared = SimpleTapGestureDelegate()
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}
